<?php

namespace mpend\controllers;

use Yii;
use yii\helpers\Html;
use yii\helpers\Url;
use mpend\components\Controller;
use yii\web\Response;
use yii\helpers\ArrayHelper;
use common\models\shop\ShopCart;
use mpend\modules\shop\models\CartSearch;
use yii\widgets\ActiveForm;

/**
 * 购物车相关接口
 * 
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class CartController extends Controller {

    /**
     * @inheritdoc
     */
    protected function rules() {
        return [
            [
                'allow' => true,
                'roles' => ['@'],
            ],
        ];
    }

    /**
     * 购物车列表
     * @return mixed
     */
    public function actionIndex() {
        $user_id = $this->token->user_id;
        ShopCart::updateAll(['status' => ShopCart::STATUS_CHECKED], [
            'user_id' => $user_id,
            'status' => ShopCart::STATUS_PREPARE_ORDER
        ]);

        /* @var $modelClass \mpend\modules\shop\models\CartSearch */
        $modelClass = new CartSearch();
        return $modelClass->search($user_id);
    }

    /**
     * 购物车物品打包结算
     * @return mixed
     */
    public function actionPack() {
        return \mpend\modules\shop\models\CartPackSearch::waitBalance($this->uid);
    }

    /**
     * actionView
     * 
     * @view view.php
     * @return mixed
     */
    public function actionView($id) {
        //轮播信息
        $directoryAsset = Yii::$app->assetManager->getPublishedUrl('@webroot/themes');
        $carouselData = [
            [
                'content' => Html::img($directoryAsset . '/images/goods/g1.jpg'),
            ],
            [
                'content' => Html::img($directoryAsset . '/images/goods/g2.jpg'),
            ],
            [
                'content' => Html::img($directoryAsset . '/images/goods/g3.jpg'),
            ],
            [
                'content' => Html::img($directoryAsset . '/images/goods/g4.jpg'),
            ],
        ];
        return $this->render('view', [
            'directoryAsset' => $directoryAsset,
            'carouselData' => $carouselData
        ]);
    }

    public function actionValidateForm($id) {
        $model = new PreduleSkuForm($id);
        if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
    }

    public function actionCreate($id) {
        $model = new PreduleSkuForm($id);
        $params = Yii::$app->request->post();
        $model->user_id = $this->uid;
        $status = false;
        if (Yii::$app->request->isPost && $model->load($params)) {
            $status = $model->save($msg);
        } else {
            $msg = '加入购物车时发生未知错误';
        }
        $num = $model->quantity;
        $num = Cart::find()->where(['user_id' => $this->uid])->sum('num');
        Yii::$app->response->format = Response::FORMAT_JSON;
        return compact('status', 'msg', 'num');
    }

    /**
     * 加入购物车
     * @return json
     */
    public function actionAdd($id, $sku = 0, $num = 1) {
        $userid = $this->uid;
        $model = Cart::findOrNew([
            'goods_id' => $id,
            'sku_id' => $sku,
            'user_id' => $userid,
        ]);
        if ($model->isNewRecord) {
            $model->num = $num;
        } else {
            $model->num += $num;
        }
        $model->status = Cart::STATUS_CHECKED;
        $status = $model->save();
        if (!$status) {
            $msg = print_r($model->errors, true);
        }
        $num = Cart::find()->where(['user_id' => $this->uid])->sum('num');
        Yii::$app->response->format = Response::FORMAT_JSON;
        return compact('status', 'msg', 'num');
    }

    /**
     * actionBalance
     * 结算提交
     * @return json
     */
    public function actionBalance() {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $goods = Yii::$app->request->post('goods');

        $status = false;
        if (!empty($goods)) {
            $result = ArrayHelper::map($goods, 'id', 'num');
            $status = Cart::preparing($this->uid, $result, $msg);
            if ($status) {
                $redirect = Url::to(['order/create']);
            }
        } else {
            $msg = '请求发送失败，未接收到结算商品信息';
        }

        return compact('status', 'redirect', 'msg');
    }

    /**
     * actionBalance
     * 结算提交
     * @return json
     */
    public function actionDelete() {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $ids = Yii::$app->request->post('ids');

        $status = false;
        if (!empty($ids)) {
            $status = Cart::deleteAll(['user_id' => $this->uid, 'id' => $ids]);
            if ($status) {
                $redirect = Url::to(['cart/index']);
            }
        } else {
            $msg = '请求发送失败，未接收到结算商品信息';
        }

        return compact('status', 'redirect', 'msg');
    }

}
